package com.kqzz.tbxt.config;


import com.kqzz.common.exception.BussinessException;
import com.kqzz.common.utils.RSAUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Date;

@Component
public class RestTemplateComponent {

    @Autowired
    RestTemplate restTemplate;
    //TODO --公司身份标识
    public static final String EAR_IDENTIFICATION = "Hyrn2021";
    //TODO --苍穹公司RSA公钥
    public static final String CQ_PUBLICKEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCZFHRqaMSSIYyh0KloEBnegF3E8oQop1Al3EWvwIN91RstJKu9bp_TiNc3OHi_lNKYLEguZFU_oYUQyTVcawen40CxPELVM1rOf8kQT_a9a_Sj_nqFkCCPhQgvh0xqIuN_zTK8hk2Fhu__GqWGEMJ79uWAEtx3nBABbXRnSmy6FQIDAQAB";



    public String earSendPost(String url, String json) throws Exception {
        HttpHeaders headers = new HttpHeaders();
        String stampe = new Date().getTime()+"";
        headers.set("stampe",stampe);
        //加密
        String jm = stampe + EAR_IDENTIFICATION;
        String token = RSAUtils.getPublicEncryptionResult(jm,CQ_PUBLICKEY);
        headers.set("token",token);
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> request = new HttpEntity<String>(json, headers);
        ResponseEntity<String> response = null;
        try {
            response = restTemplate.postForEntity(url, request, String.class);
        }catch (Exception e){
            throw new BussinessException("通信失败");
        }
        //4、获取http状态码
        int statusCodeValue = response.getStatusCodeValue();
        if(statusCodeValue!=200){
            throw new BussinessException("通信失败");
        }

        return response.getBody();
    }






}
